#!/bin/bash
# Normalize hosts file.
# https://github.com/racaljk/hosts

date_amend()
{
	# check if hosts file changes
	if git diff --exit-code "$1" > /dev/null; then
		# hosts file is not changed, correct to git log records.
		local repo_date=$(git log --date=short -n1 "$1" |
					grep -Pom1 "\d+-\d+-\d+")
		perl -pe "s|\d{4}-\d{2}-\d{2}|$repo_date|" "$1" > h.swp
		mv -f h.swp "$1"
	else
		# hosts file has been changed, correct to system date.
		perl -pe "s|\d{4}-\d{2}-\d{2}|$(date +%F)|" "$1" > h.swp
		mv -f h.swp "$1"
	fi
}

eol_amend()
{
	# In case people don't have dos2unix.
	cat "$1" | tr -d '\r' > h.swp
	mv -f h.swp "$1"
}

style_amend()
{
	perl -pe "s|((\d+\.){3}\d+)\s+|\1\t|g" "$1" > h.swp
	perl -pe "s|^[ \t]+\|[ \t]+$||g" h.swp > "$1"
	rm -f h.swp
}

if [ -z "$1" ]; then
	echo "Usage: $0 [hosts-file]"
	exit 1
fi

eol_amend "$1"
date_amend "$1"
style_amend "$1"
